package com.cavy.platform.client.service;

import com.cavy.platform.client.CavyConfig;
import com.cavy.platform.client.dto.AgentRegisterDto;
import com.sun.management.OperatingSystemMXBean;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author 唐旭
 * @Date 2018/7/27
 */
@Service
@Data
public class SystemInfoService {
    private String hostName;
    private String hostAddress;
    private String osName;
    private String osVersion;
    //单位MB
    private long totalPhysicalMemorySize;
    private OperatingSystemMXBean operatingSystemMXBean;
    @Autowired
    private CavyConfig cavyConfig;

    @PostConstruct
    public void init() throws UnknownHostException {
        InetAddress addr = InetAddress.getLocalHost();
        this.hostName = addr.getHostName();
        this.hostAddress = addr.getHostAddress();
        this.osName = System.getProperty("os.name");
        this.osVersion = System.getProperty("os.version");
        operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
        totalPhysicalMemorySize = operatingSystemMXBean.getFreePhysicalMemorySize() / 1024 / 1024;
    }

    public long getFreeMemory() {
        return operatingSystemMXBean.getFreePhysicalMemorySize() / 1024 / 1024;
    }

    public AgentRegisterDto buildAgentRegisterDto() {
        return new AgentRegisterDto().setHostname(hostName).setAddress(hostAddress)
                .setSystemName(osName + osVersion).setMaxMemory(totalPhysicalMemorySize)
                .setMaxJobCount(cavyConfig.getMaxJobCount())
                .setAgentVersion("1.0");
    }
}
